<template>
  <div>
    <el-form>
      <el-form-item>
        <el-button type="primary" @click="addContract()">新增</el-button>
      </el-form-item>
    </el-form>
    <el-dialog :title="dialogType === 'add'?'新增质保':'编辑质保'" :visible.sync="SettingVisible" :close-on-click-modal="false" :beforeClose="cancel">
      <el-form :model="warrantyDto" :rules="roleRules" ref="warrantyForm" label-width="120px">
        <el-form-item label="省份" prop="province">
          <el-form-item>
            <el-select v-model="warrantyDto.provinceCode" clearable placeholder="请选择省份" @change="onSearchSelected()">
              <el-option
                v-for="item in allProvince"
                :key="item.code"
                :label="item.name"
                :value="item.code">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form-item>
        <el-form-item label="运营商" prop="customerId">
          <el-select v-model="warrantyDto.customerId" placeholder="请选择运营商">
            <el-option v-for="item in carrierOperatorList"
                       :key="item.id"
                       :label="item.company"
                       :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="合同编号" prop="contractId">
          <el-select v-model="warrantyDto.contractId" placeholder="请选择合同编号" @change="contractChange"
                     :disabled="dialogType === 'edit'" :auto-complete="true">
            <el-option v-for="item in contractList"
                       :key="item.id"
                       :label="item.contractNumber"
                       :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="生产批次号" prop="productionId">
          <el-select v-model="warrantyDto.productionId" placeholder="请选择生产批次号" :disabled="dialogType === 'edit'">
            <el-option v-for="item in productionList"
                       :key="item.id"
                       :label="item.orderNumber"
                       :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="保修起始条件" prop="startRepairStatus">
          <el-select v-model="warrantyDto.startRepairStatus" placeholder="请选择保修起始条件">
            <el-option value="0" key="0" label="生产日期"></el-option>
            <el-option value="1" key="1" label="发货日期"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="保修周期(天)" prop="warrantyDay">
          <el-input-number v-model.number="warrantyDto.warrantyDay" :min="1" :step="1"></el-input-number>
        </el-form-item>
        <el-form-item label="品牌" prop="brandId">
          <el-select v-model="warrantyDto.brandId" placeholder="请选择品牌" @change="brandChange">
            <el-option v-for="item in brandOptions"
                       :label="item.name"
                       :value="item.id"
                       :key="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="型号" prop="modelId">
          <el-select v-model="warrantyDto.modelId" placeholder="请选择型号">
            <el-option v-for="item in modelOptions"
                       :key="item.id"
                       :label="item.code"
                       :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="warrantyDto.remark"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="cancel()">取消</el-button>
        <el-button type="primary" @click="submit()">确定</el-button>
      </div>
    </el-dialog>
    <custom-table
      :data="warrantyList"
      :columns="columns"
      :operationColumn="operationColumns"
      :pagination="pagination"
    >
    </custom-table>
  </div>
</template>
<script>
  import CustomTable from '@/components/table/CustomTable'
  import { apiGetModelList } from '@/api/dictionary'
  import { apiGetClientList } from '@/api/basic/info/client'
  import { apiAddWarranty, apiGetWarrantyList, apiUpdWarranty, apiGetWarrantyById, apiDelWarranty } from '@/api/warranty/set'
  import { getUserId, getName } from '@/utils/token'
  import { apiGetContractList } from '@/api/warranty/contract'
  import { parseTime } from '@/utils'
  import { apiGetProductionOrderList } from '@/api/warranty/order'
  import {apiGetCity} from '@/api/dictionary'

  export default {
    components: {
      CustomTable
    },
    created() {
      let listQuery = {
        pageNumber: 1,
        pageSize: 10
      }
      this.getWarrantyList(listQuery)
      this.getAllProvince()
    },
    data() {
      return {
        columns: [
          {label: '质保编号', name: 'warrantyNumber', align: 'center'},
          {label: '省份', name: 'province', align: 'center'},
          {label: '运营商', name: 'customer', align: 'center'},
          {label: '合同编号', name: 'contract', align: 'center'},
          {label: '生产批次号', name: 'production', align: 'center'},
          {label: '保修起始条件', name: 'startRepairStatus', align: 'center'},
          {label: '保修周期(天)', name: 'warrantyDay', align: 'center'},
          {label: '品牌', name: 'brand', align: 'center'},
          {label: '型号', name: 'model', align: 'center'},
          {label: '备注', name: 'remark', align: 'center'}
        ],
        allProvince: [],
        contractList: this.getContractList(),
        warrantyDto: {
          provinceCode: '',
          province: '',
          customerId: '',
          contractId: '',
          productionId: '',
          startRepairStatus: '',
          warrantyDay: 0,
          modelId: '',
          brandId: '',
          remark: '',
          warrantyNumber: '',
          proposerId: getUserId(),
          proposerName: getName()
        },
        SettingVisible: false,
        operationColumns: {
          width: '100',
          operations: [
            {name: '编辑', callback: this.handelEdit},
            {name: '删除', callback: this.handleDel}
          ]
        },
        roleRules: {
          contractId: [{required: true, message: '请选择合同编号', trigger: 'blur'}],
          productionId: [{required: true, message: '请选择生产批次号', trigger: 'blur'}],
          province: [{required: true, message: '请选择省份', trigger: 'blur'}],
          startRepairStatus: [{required: true, message: '请选择保修起始条件', trigger: 'blur'}],
          warrantyDay: [{required: true, message: '请输入保修周期', trigger: 'blur'}],
          remark: [{max: 255, message: '长度不得超过255字符', trigger: 'blur'}]
        },
        dialogType: 'add',
        modelOptions: [],
        brandOptions: this.getBrandList(),
        carrierOperatorList: [],
        warrantyList: [],
        pagination: this.getData(this.getWarrantyList),
        productionList: []
      }
    },
    methods: {
      getAllProvince () {
        apiGetCity().then(response => {
          this.allProvince = response.data
        })
      },
      addContract () {
        this.dialogType = 'add'
        this.SettingVisible = true
      },
      handelEdit (row) {
        this.SettingVisible = true
        this.dialogType = 'edit'
        var that = this
        let listQuery = {
          id: row.id
        }
        apiGetWarrantyById(listQuery).then(rsp => {
          let data = rsp.data
          this.warrantyDto = rsp.data
          if (this.warrantyDto.customerId == '0') {
            this.warrantyDto.customerId = undefined
          }
          if (this.warrantyDto.brandId == '0') {
            this.warrantyDto.brandId = undefined
          }
          if (this.warrantyDto.modelId == '0') {
            this.warrantyDto.modelId = undefined
          }
          let customerListQuery = {
            provinceCode: this.warrantyDto.provinceCode,
            customerType: 1,
            roleType: 1
          }
          this.getClientList(customerListQuery)
          let search = this.getModelList({brandId: data.brandId})
          search.then(function(value) {
            that.modelOptions = value
            value.forEach(function(item) {
              if (item.id === data.modelId) {
                that.warrantyDto.modelId = data.modelId
              }
            })
          })
          // 获取生产批次号列表
          let listQuery = {
            contractId: this.warrantyDto.contractId
          }
          apiGetProductionOrderList(listQuery).then(rsp => {
            this.productionList = rsp.data
          })
        })
        this.warrantyDto.proposerId = getUserId()
        this.warrantyDto.proposerName = getName()
      },
      onSearchSelected() {
        this.warrantyDto.customerId = undefined
        let listQuery = {
          provinceCode: this.warrantyDto.provinceCode,
          customerType: 1,
          roleType: 1
        }
        this.getClientList(listQuery)
      },

      brandChange (val) {
        var that = this
        var search = this.getModelList({brandId: val})
        search.then(function (value) {
          that.modelOptions = value
          if (that.warrantyDto.brandId === null || that.warrantyDto.brandId === undefined) {
            that.warrantyDto.modelId = undefined
          } else {
            var oldModleId = that.warrantyDto.modelId
            that.warrantyDto.modelId = undefined
            value.forEach(function (item) {
              if (item.id === oldModleId) {
                that.warrantyDto.modelId = oldModleId
              }
            })
          }
        })
      },
      submit () {
        this.$refs['warrantyForm'].validate((valid) => {
          if (valid) {
            if (this.dialogType === 'add') {
              this.addSubmit()
            } else {
              this.updSubmit()
            }
          } else {
            return false
          }
        })
      },
      getClientList (listQuery) {
        apiGetClientList(listQuery).then(response => {
          this.carrierOperatorList = response.data
        }).catch(() => {
        })
      },
      addSubmit() {
        apiAddWarranty(this.warrantyDto).then(() => {
          this.$message({
            message: '添加质保成功',
            type: 'success'
          })
          this.SettingVisible = false
          this.getWarrantyList()
          this.$refs['warrantyForm'].resetFields()
        }).catch(() => {
        })
      },
      getContractList() {
        apiGetContractList().then(rsp => {
          this.contractList = rsp.data
        }).catch(() => {
        })
      },
      updSubmit() {
        apiUpdWarranty(this.warrantyDto).then(() => {
          this.$message({
            message: '修改质保信息成功',
            type: 'success'
          })
          this.SettingVisible = false
          this.getWarrantyList()
          this.$refs['warrantyForm'].resetFields()
        }).catch(() => {
        })
      },
      getWarrantyList(listQuery) {
        apiGetWarrantyList(listQuery).then(rsp => {
          this.warrantyList = rsp.data
          this.pagination.totalRecords = rsp.totalRecords
          for (let i in this.warrantyList) {
            if (this.warrantyList[i].startRepairStatus === '0') {
              this.warrantyList[i].startRepairStatus = '生产日期'
            } else if (this.warrantyList[i].startRepairStatus === '1') {
              this.warrantyList[i].startRepairStatus = '发货日期'
            } else {
              this.warrantyList[i].startRepairStatus = ''
            }
          }
        }).catch(() => {
        })
      },
      contractChange() {
        let listQuery = {
          contractId: this.warrantyDto.contractId
        }
        apiGetProductionOrderList(listQuery).then(rsp => {
          this.productionList = rsp.data
        })
        this.warrantyDto.productionId = undefined
      },
      handleDel (row) {
        this.$confirm('确定删除该质保信息?', '删除质保信息', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let listQuery = {
            id: row.id
          }
          apiDelWarranty(listQuery).then(rsp => {
            if (rsp.data !== undefined && rsp.data.status === 'error') {
              this.$message({
                showClose: true,
                type: 'error',
                message: rsp.data.message
              })
            } else if (rsp.resCode === '200') {
              this.$message({
                showClose: true,
                type: 'success',
                message: '删除成功!'
              })
            }
            this.getWarrantyList()
          })
        }).catch(() => {
        })
      },
      cancel() {
        this.SettingVisible = false
        this.$refs['warrantyForm'].resetFields()
        this.warrantyDto.provinceCode = undefined
      }
    }
  }
</script>
